<template>
	<div class="container-fluid">
		<el-row :gutter="20">
			<el-col :span="6">
				<div class="grid-content bg-purple">
					<div class="panel">
						<div class="panel-heading">
							<el-row>
								<el-col :span="8">
									<div class="grid-content bg-purple">
										<h3 class="panel-title">任务分类</h3>
									</div>
								</el-col>
								<el-col :span="16">
									<div class="grid-content bg-purple pull-right">
										<el-button-group>
											<el-button size="mini" icon="el-icon-plus" plain @click="createCategory"></el-button>
											<el-button size="mini" icon="el-icon-edit-outline" :disabled="!editCategoryParams.name" plain @click="editCategory"></el-button>
											<el-button size="mini" icon="el-icon-delete" :disabled="!editCategoryParams.name" plain @click="deleteCategory"></el-button>
										</el-button-group>
									</div>
								</el-col>
							</el-row>
						</div>
						<div class="panel-body">
							<el-table ref="singleTable" :data="categories" highlight-current-row style="width: 100%" @row-click="fenLeiClick" @current-change="handleCurrentChangeFenLei">
								<el-table-column prop="bh" label="编号"></el-table-column>
							    <el-table-column prop="name" label="名称"></el-table-column>
							    <el-table-column prop="tasks.length" label="绑定数"></el-table-column>
							</el-table>
						</div>
					</div>
				</div>
			</el-col>
			<el-col :span="18">
				<div class="grid-content bg-purple">
					<div class="panel">
						<div class="panel-heading">
							<el-row class="heading-row">
								<el-col :span="4">
									<div class="grid-content bg-purple">
										<h3 class="panel-title">任务列表</h3>
									</div>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<collapse-view content="高级搜索">
										<el-form label-width="50px" label-position="right" :inline="true">
											<el-form-item label="名称">
												<el-input v-model="queryParams.name" placeholder="输入任务名称查询" clearable></el-input>
											</el-form-item>
											<el-form-item label="类型">
												<el-select v-model="queryParams.type" placeholder="选择任务类型查询" clearable>
													<el-option v-for="item in typesSearch" :key="item.value" :label="item.label" :value="item.value"></el-option>
												</el-select>
											</el-form-item>
											<el-form-item label="是否必填" label-width="80px">
												<el-switch v-model="queryParams.required" active-color="#13ce66" inactive-value=""></el-switch>
											</el-form-item>
											<el-form-item label="是否上传图片" label-width="100px">
												<el-switch v-model="queryParams.photo" active-color="#13ce66" inactive-value=""></el-switch>
											</el-form-item>
											<el-form-item label="是否有效" label-width="70px">
												<el-switch v-model="queryParams.effective" active-color="#13ce66" inactive-value=""></el-switch>
											</el-form-item>
											<el-form-item>
												<el-button @click="fetchTasks">搜索</el-button>
												<el-button @click="clearSearchForm">清除</el-button>
											</el-form-item>
										</el-form>
									</collapse-view>
								</el-col>
							</el-row>
						</div>
						<div class="panel-body">
							<el-table ref="taskTable" :data="tasks.data" :row-key="getRowKey" style="width: 100%" @selection-change="handleSelectionChange" v-loading="taskTableLoading" @select="attachToCategory" @select-all="attachToCategory">
								<el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
								<el-table-column prop="name" label="名称"></el-table-column>
								<el-table-column label="类型" width="100">
									<template slot-scope="scope">
										<span v-html="randerTableType(scope.row)"></span>
									</template>
								</el-table-column>
								<el-table-column label="是否必填" width="100">
									<template slot-scope="scope">
										<span v-html="scope.row.required ? '是' : '否'"></span>
									</template>
								</el-table-column>
								<el-table-column label="是否上传图片" width="120">
									<template slot-scope="scope">
										<span v-html="scope.row.photo ? '是' : '否'"></span>
									</template>
								</el-table-column>
								<el-table-column label="开始时间" width="100">
									<template slot-scope="scope">
										<span v-html="scope.row.start_time ? scope.row.start_time.substr(0, 10) : '未设置'"></span>
									</template>
								</el-table-column>
								<el-table-column label="结束时间" width="100">
									<template slot-scope="scope">
										<span v-html="scope.row.end_time ? scope.row.end_time.substr(0, 10) : '永久生效'"></span>
									</template>
								</el-table-column>
							</el-table>
						</div>
						<div class="panel-footer text-right">
							<el-button type="primary" plain class="pull-left" @click="submitAttachToCategory">保存修改</el-button>
							<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
														 :current-page="queryParams.page"
														 :page-sizes="[10, 20, 50, 100]"
														 :page-size="queryParams.paginate"
														 layout="total, sizes, prev, pager, next, jumper"
														 :total="tasks.total">
							</el-pagination>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
		<!--Form-->
		<el-dialog title="创建分类" :visible.sync="createCategoryForm" width="400px" @close="handleCreateCategoryFormClose">
			<el-form ref="createCategory" :model="createCategoryParams" :rules="categoryRules">
				<el-form-item label="分类名称" label-width="80px" prop="name">
					<el-input v-model="createCategoryParams.name" :autofocus="true"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="createCategoryForm = false">取 消</el-button>
				<el-button type="primary" @click="submitCreateCategory">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="编辑分类" :visible.sync="editCategoryForm" width="400px" @close="handleEditCategoryFormClose">
			<el-form ref="editCategory" :model="editCategoryParams" :rules="categoryRules">
				<el-form-item label="分类名称" label-width="80px" prop="name">
					<el-input v-model="editCategoryParams.name"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="editCategoryForm = false">取 消</el-button>
				<el-button type="primary" @click="submitEditCategory">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import Vue from 'vue'
	import api from '../apis'
	import task from "../apis/modules/task";

	export default {
		name: "category",
		data () {
			return {
				loading: false,
				taskTableLoading: false,
				createCategoryForm: false,
				editCategoryForm: false,
				search: '',
				categories: [],
				tasks: {
					data: [],
					total: 0
				},
				createCategoryParams: {
					name: '',
					scope: 'task'
				},
				categoryRules: {
					name: [
						{ required: true, message: '请输入分类名称', trigger: 'blur' }
					]
				},
				editCategoryParams: {
					name: '',
				},
				props: {
					children: 'children',
					label: 'name'
				},
				typesSearch: [
					{
						value: '',
						label: '全部'
					},
					{
						value: 'number',
						label: '数量'
					},{
						value: 'branch',
						label: '打分'
					},{
						value: 'text',
						label: '文本'
					},{
						value: 'select',
						label: '选择器'
					},{
						value: 'date',
						label: '日期'
					}
				],
				multipleSelection: [],
				selectionStore: [],
				queryParams: {
					page: 1,
					paginate: 10,
					name: '',
					type: '',
					required: false,
					photo: false
				},
				getRowKey (row) {
					return row.id;
				}
			}
		},
		methods: {
			/**
			 * 商店分类点击重新查询
			 */
			fenLeiClick (row, event, column) {
				this.editCategoryParams = row;
				this.selectNodeHandle(row);
			},
			/**
			 * 商店分类默认选中第几行
			 */
			setCurrent(row) {
		        this.$refs.singleTable.setCurrentRow(row);
		    },
		    handleCurrentChangeFenLei(val){
		    	this.currentRow = val;
		    },
			/**
			 * 获取分类数据
			 */
			fetchCategory () {
				this.loading = true;
				api.category.fetch({
					scope: 'task'
				}).then(response => {
					for (var i = 0; i < response.data.length; i++) {
						response.data[i]['bh'] = (i+1);
					}
					this.categories = response.data;
					this.loading = false;
				}).catch(errors => {
					this.$message.error(errors.response.data.error);
				})
			},
			/**
			 * 获取任务数据
			 */
			fetchTasks () {
				this.taskTableLoading = true;
				api.task.fetch(this.queryParams).then(response => {
					this.tasks = response.data;
					this.taskTableLoading = false;
				});
			},
			/**
			 * 渲染类型
			 */
			randerTableType (row) {
				switch (row.type) {
					case 'number':
						return '数字';
					case 'text':
						return '文本';
					case 'select':
						return '选择器';
					case 'date':
						return '日期';
					default:
						return '未知类型';
				}
			},
			/**
			 * 改变任务列表分页大小时触发
			 */
			handleSizeChange (size) {
				this.queryParams.paginate = size;
				this.fetchTasks();
			},
			/**
			 * 改变任务列表页码时触发
			 */
			handleCurrentChange (index) {
				this.queryParams.page = index;
				this.fetchTasks();
			},
			/**
			 * 获取被选中的任务
			 */
			handleSelectionChange (rows) {
				this.multipleSelection = rows;
			},
			/**
			 * 绑定任务到分类
			 */
			submitAttachToCategory () {
				if (this.editCategoryParams.hasOwnProperty('id')) {
					let tasks = [];
					this.multipleSelection.forEach(item => {
						tasks.push(item.id);
					});
					//请求API绑定任务到分类
					api.category.attachTaskById(this.editCategoryParams.id, {
						tasks: tasks
					}).then(() => {
						this.fetchCategory();
						this.$message.success('关联任务成功');
					}).catch(errors => {
						this.$message.error(errors.response.data.error);
					});
				}
			},
			/**
			 * 获取选中的分类节点
			 */
			selectNodeHandle (item) {
				this.editCategoryParams = item;
				api.category.fetchByID(item.id, {
					only_tasks: true
				}).then(response => {
					this.toggleSelection([]);
					this.multipleSelection = response.data;
					this.toggleSelection(this.multipleSelection);
				}).catch(errors => {
					this.$message.warning(errors.response.data.error);
				});
			},
			/**
			 * 将任务关联到分类
			 */
			attachToCategory (selection, row) {
				if (!this.editCategoryParams.hasOwnProperty('id')) {
					this.$message.warning('请选择分类后再勾选需要关联的任务');
					this.toggleSelection([]);
				}
			},
			/**
			 * 选中或取消选选中表格
			 */
			toggleSelection (rows) {
				if (rows.length > 0) {
					for(let i = 0; i < rows.length; i ++) {
						for (let j = 0; j < this.tasks.data.length; j ++) {
							if (rows[i].id === this.tasks.data[j].id) {
								this.$refs['taskTable'].toggleRowSelection(this.tasks.data[j], true);

							}
						}
					}
				} else {
					this.$refs['taskTable'].clearSelection();
				}
			},
			/**
			 * 创建分类
			 */
			createCategory () {
				this.createCategoryForm = true;
			},
			/**
			 * 编辑分类
			 */
			editCategory () {
				if (this.editCategoryParams.name) {
					this.editCategoryForm = true;
				} else {
					this.$message.warning('请选择分类后再点击编辑');
				}
			},
			/**
			 * 删除分类
			 */
			deleteCategory () {
				/**
				 * 判断是否选中分类节点
				 */
				if (this.editCategoryParams.name) {
					this.$confirm('此操作将删除分类信息, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						api.category.destroy(this.editCategoryParams.id).then(() => {
							//遍历分类集合删除指定的ID的分类
							for (let i = 0; i <= this.categories.length; i++) {
								if (this.categories[i].id === this.editCategoryParams.id) {
									Vue.delete(this.categories, i);
								}
							}
							this.$message.success('删除成功');
						}).catch(errors => {
							this.$message.error(errors.response.data.error);
						})
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
				}
			},
			/**
			 * 提交创建分类的信息
			 */
			submitCreateCategory () {
				this.$refs['createCategory'].validate((valid) => {
					if (valid) {
						api.category.store(this.createCategoryParams).then(response => {
							this.handleCreateCategoryFormClose();
							this.$message.success('分类创建成功');
							let category = {...response.data};
							category.bh = this.categories.length + 1;
							category.tasks = [];
							this.categories.push(category);
						}).catch(errors => {
							this.$message.error(errors.response.data.error);
						});
					} else {
						return false;
					}
				});
			},
			/**
			 * 提交修改分类信息
			 */
			submitEditCategory () {
				this.$refs['editCategory'].validate((valid) => {
					if (valid) {
						api.category.update(this.editCategoryParams.id, {
							name: this.editCategoryParams.name
						}).then(response => {
							this.handleEditCategoryFormClose();
							// Vue.set();
							this.$message.success('分类创建成功');
						}).catch(errors => {
							this.$message.error(errors.response.data.error);
						});
					} else {
						return false;
					}
				});
			},
			/**
			 * 当创建分类的窗口关闭时清空表单内容
			 */
			handleCreateCategoryFormClose () {
				this.createCategoryForm = false;
				this.$refs['createCategory'].resetFields();
			},
			/**
			 * 当编辑分类的窗口关闭时清空表单内容
			 */
			handleEditCategoryFormClose () {
				this.editCategoryForm = false;
			},
			/**
			 * 清除表单内容
			 */
			clearSearchForm () {
				this.queryParams.name = '';
				this.queryParams.type = '';
				this.queryParams.required = '';
				this.queryParams.photo = '';
				this.fetchTasks();
			}
		},
		mounted () {
			/**
			 * 获取数据
			 */
			this.fetchCategory();
			this.fetchTasks();
		}
	}
</script>

<style>

</style>
